package com.qdxwx.manage.aspectj;



import com.qdxwx.common.exception.PermissionException;
import com.qdxwx.common.utils.TKServlet;
import com.qdxwx.common.annotation.Logical;
import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.manage.support.SessionUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Set;

/**
 * @author ZhiYong
 * @createTime 2021/3/16
 * @description
 */
@Order(1)
@Aspect
@Component
public class PermissionAspect {

    private static final Logger logger = LoggerFactory.getLogger(PermissionAspect.class);
    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @Before("@annotation(com.qdxwx.common.annotation.Permissions)")
    public void doBefore(JoinPoint joinPoint) throws Exception {
        // 获得注解
        Permissions perms = getAnnotationLog(joinPoint);
        if (perms == null) {
            throw new PermissionException("无此操作权限！");
        }
        HttpServletRequest request = TKServlet.getRequest();
        // 获取当前的用户
        if (SessionUtils.isAdmin(request)) {
            return;
        }
        Set<String> permissions = SessionUtils.getPermissions(request);
        if (permissions == null) {
            throw new PermissionException("无此操作权限！");
        }
        if (perms.logical() == Logical.AND) {
            for (String perm : perms.value()) {
                if (!permissions.contains(perm)) {
                    throw new PermissionException("无此操作权限！");
                }
            }
        } else {
            for (String perm : perms.value()) {
                if (permissions.contains(perm)) {
                    return;
                }
            }
            throw new PermissionException("无此操作权限！");
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Permissions getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(Permissions.class);
        }
        return null;
    }
}
